/**
 * Description
 *
 * Creation Date 22/12/2017
 * @author Candy
 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
	StyleSheet,
	View,
	Image,
	TouchableOpacity,
	Platform,
	Button,
	TextInput,
	Text
} from 'react-native';
import { NavigationActions } from 'react-navigation';
import { connect } from 'react-redux';
import Icon from 'react-native-vector-icons/Ionicons';
import { screen, color, config } from '../../utils';
import ButtonItem from '../../components/ButtonItem';
import { setStore, getStore, removeStore } from '../../utils/tools';
import { InitCart, AddToCart, ReduceToCart, GoToPay, removeCart } from '../../redux/actions/rootActions';


class CartScreen extends Component {
	static navigationOptions = ({ navigation }) => ({
		headerTitle: (
			<TouchableOpacity style={ styles.gridContainer }>
				<Image resizeMode='stretch' source={{uri: 'https://4eb7f3de389ff6b61816-1dd1d9fd8ad438da629d92a7640b81cb.ssl.cf1.rackcdn.com/GDR2016/GDR477/DESKTOP/Ten_Years_Logo_9.png?param=100y20'}}
					   style={{width: screen.width/2.5, height: 30, marginTop: 5}} />
			</TouchableOpacity>
		),
	});

	static contextTypes = {
		store: PropTypes.any
	}

	constructor(props, context) {
		super(props, context);
		this.text = 0;
	}

	componentWillMount() {
	}

	goBack = () => {
		const backAction = NavigationActions.back({
			key: this.props.navigation.state.key,
		});
		console.log(backAction)
		this.props.navigation.goBack();
	}

	componentDidMount() {
		this.props.InitCart();
	}
	onChangeText = () => {}

	async AddNum(productData) {
		await this.props.AddToCart(productData);
	}

	async goToPay(totalPrice) {
		await getStore('user_id').then( user => {
			this.props.GoToPay(totalPrice);
			if(user) {
				this.props.navigation.navigate('PaymentDetail')
			} else {
				this.props.navigation.navigate('LoginDetail', {title: 'payment'})
			}
		}).catch(err => {
			console.log(err)
			this.props.navigation.navigate('LoginDetail', {title: 'payment'})
		})

		this.props.removeCart('cartList');

	}

	async reduceNum(productData) {
		await this.props.ReduceToCart(productData);
	}

	render () {
		const { cartList } = this.context.store.getState().cartReducers;
		let cartListData = [];
		let totalPrice = 0;
		if(cartList) {
			cartListData= Object.values(cartList);
			cartListData.forEach(item => {
				totalPrice += item.num * item.price
			})
		}
		return (
			<View style={styles.container}>
				{
					cartListData && cartListData.length > 0 && cartListData.map((item, index) => (
						<View key={index} style={styles.gridContainer}>
							<View style={{width: screen.width /2 - 20}}>
								<Image style={styles.brandImage} resizeMode='stretch'
									   source={{uri: config.productBaseUrl + item.product_image + '?param=350y150'}} />
								<Text style={styles.textStyle}> {item.product_name}</Text>
							</View>
							<View style={{width: screen.width/2 - 20}}>
								<View style={styles.gridContainer}>
									<TouchableOpacity onPress={() => this.AddNum(item)}>
										<Icon name="ios-add-circle-outline" size={30} color={color.black} />
									</TouchableOpacity>
									<TextInput
										style={{width: 35, height: 25, marginRight: 15, marginLeft:15, borderColor: 'gray', borderWidth: 1, textAlign: 'center'}}
										// onChangeText={(text) => this.setState({text})}
										value={String(item.num)}
									/>
									<TouchableOpacity onPress={() => this.reduceNum(item)}>
										<Icon name="ios-remove-circle-outline" size={30} color={color.black} />
									</TouchableOpacity>
								</View>
								<Text style={styles.price}> ￥{item.price}</Text>
							</View>
						</View>
					))
				}
				{
					cartListData && cartListData.length > 0 && <View style={[styles.gridContainer, {borderTopWidth: 1, borderColor: '#acacac', marginTop: 20, paddingRight: 15, paddingLeft: 15}]}>
						<Text style={{fontSize: 20}}>Total</Text>
						{
							totalPrice > 0 && <Text style={{fontSize: 25, fontWeight: 'bold', color: color.theme}}>￥{ totalPrice }</Text>
						}
					</View>
				}
				{
					cartListData.length == 0 && <View style={{width: screen.width, marginTop: 30}}><Text style={{textAlign:'center'}}>还没有添加什么商品！</Text></View>
				}
				{
					cartListData.length == 0 && <ButtonItem buttonText="GO TO HOME" onPress={() => this.props.navigation.navigate('Home')} style={{backgroundColor: '#B8B8B8'}} />
				}
				{
					cartListData && cartListData.length > 0 && <ButtonItem buttonText="CHECKOUT" onPress={() => this.goToPay(totalPrice)} />
				}
			</View>
		)
	}
}

//连接reducer
export default connect((state) => {
	const { cartReducers } = state;  // 这里的beautyReducers注意和对应的reducer文件export的类相同
	return {
		cartReducers,
		cartList: cartReducers.cartList
	}
}, { InitCart, AddToCart, ReduceToCart, GoToPay, removeCart })(CartScreen) // 这里是对应的存值的方法,导出当前模块


const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: color.backgroundColor
	},
	gridContainer: {
		marginRight: 20,
		marginLeft: 20,
		paddingTop: 5,
		paddingBottom: 5,
		flexDirection: 'row',
		flexWrap: 'wrap',
		alignItems: 'center',
		justifyContent: 'space-between'
	},
	textStyle:{
		width:screen.width/2,
		alignItems:'center',
		justifyContent: 'center'
	},
	brandImage: {
		width: 150,
		height: 80
	},
	price: {
		fontSize: 18,
		textAlign: 'center',
		fontWeight: 'bold'
		// color: color.theme
	}
});